<template>
  <div class="page-controller">
    <category-tree />
    <!-- 查询条件区 -->
    <div class="page-form">
      <FISearchForm
        class="page-form__query"
        ref="ruleFormRef"
        :id="`inqu_${tableId}`"
        :searchNum="getHasSearchValues(state.query)"
        v-model:form-value="state.query"
        :defaultFormNum="4"
        :table-column="columns"
        :wrapperSpan="searchWrapperSpan"
        @submit="searchFn"
      >
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem prop="processDefinitionKey" label="流程编码">
            <FIInput v-model="state.query.processDefinitionKey" clearable />
          </FIFormItem>
        </el-col>
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem name="processDefinitionName" label="流程名称">
            <FIInput v-model="state.query.processDefinitionName" clearable />
          </FIFormItem>
        </el-col>
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem name="status" label="发布状态">
            <FISelect
              v-model="state.query.status"
              valueCustom="value"
              :options="[
                { value: '', label: '全部' },
                { value: 'draft', label: '未发布' },
                { value: 'published', label: '已发布' },
              ]"
              clearable
            />
          </FIFormItem>
        </el-col>
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem name="enable" label="启用状态">
            <FISelect
              v-model="state.query.enable"
              valueCustom="value"
              :options="[
                { value: '', label: '全部' },
                { value: 'Y', label: '启用' },
                { value: 'N', label: '停用' },
              ]"
              clearable
            />
          </FIFormItem>
        </el-col>
      </FISearchForm>
      <!-- 查询结果列表区 -->
      <FITable
        ref="tableRef"
        class="bpage-form__query margin-top20"
        title="记录集"
        :id="`result_${tableId}`"
        :readonly="false"
        :data="state.dataList"
        primaryKey="formId"
        v-model:columns="columns"
        :isLoading="isTableLoading"
        insertable
        :saveSuccessful="saveSuccessful"
        :pageConfig="pageConfig"
        @row-add-save="handleSave"
        @table-refresh="searchFn"
        @selection-change="handleSelectionChange"
        @size-change="handleSizeChange"
        @current-page-change="handleCurrentChange"
        @action-click="handleAction"
      >
        <!-- FITable组件每一列都可以自定义，插槽名称为列数据的 prop值 -->
        <!-- 自定义列 moduleEname1 -->
        <template #moduleEname1="{ scope }">
          <FISelect
            @change="onCellChange"
            v-if="scope.row.isSelected"
            v-model="scope.row.moduleEname1"
            valueCustom="value"
            :options="arr3"
            clearable
          />
          <span v-else>{{ scope.row.moduleEname1 }}</span>
        </template>
        <template #moduleEname2="{ scope }">
          <FISelect
            v-if="scope.row.isSelected"
            v-model="scope.row.moduleEname2"
            valueCustom="value"
            :options="scope.row.moduleEname1Options"
            clearable
          />
          <span v-else>{{ scope.row.moduleEname2 }} </span>
        </template>
        <template #iconInfo="{ scope }">
          <FIIconInput v-if="scope.row.isSelected" v-model="scope.row.iconInfo"></FIIconInput>
          <span v-else>{{ scope.row.iconInfo }}</span>
        </template>
        <template #headerBtn>
          <FIPopconfirmBtn
            title="您是否确认删除选中数据吗？"
            beforePopText="请选择一条数据"
            buttonText="删除"
            :btn-binds="{ id: 'delete', border: true }"
            :isVisible="!!checkedRows.length"
            @confirm="deleteRow"
          />
        </template>
      </FITable>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed } from 'vue'
import CategoryTree from '../components/CategoryTree.vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import { apiGetfrontPrjMaint, apiGetlistAllModule1, apiGetModule2 } from '@/api/configEnvMaint/index'
import { apiRequestPost } from '@/api/globalApi.js'
import { useMessage } from '@/hooks/message' // 通用message消息提示框
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData, getHasSearchValues } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import FIIconInput from '@/components/FIIconInput.vue'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
// 路由对象
const route = useRoute()
// el-col span栅格占据的列数
const searchWrapperSpan = 8
// 表格是否显示加载中
const isTableLoading = ref(false)
// 页面编码
const tableId = 'ProcessDef'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
// 表格对象
const tableRef = ref(null)
const state = reactive({
  // 查询条件
  query: {
    processDefinitionKey: '', // 流程编码
    processDefinitionName: '', // 流程名称
    status: '', // 发布状态
    enable: '', // 启动状态
    categoryId: '', // 目录id
    dynamicParams: [],
    orderbyParams: [],
    current: 1,
    size: 10,
  },
  // 表格数据
  dataList: [],
})
// 页面配置
const pageConfig: PageConfig = reactive({
  total: 0, // 总条数
  currentPage: 1, // 当前页码
})
// 表格列数据
const columns: Column[] = reactive([
  { label: '流程编码', prop: 'ProcessDefinitionName', align: 'center', width: '150' },
  { label: '流程名称', prop: 'ProcessDefinitionDisplayName', align: 'center', width: '150' },
  {
    label: '状态',
    prop: 'ProcessStatus',
    align: 'center',
    width: '80',
    editType: 'select',
    options: [
      { label: '', value: '' },
      { label: '未发布', value: 'draft' },
      { label: '已发布', value: 'published' },
    ],
  },
  {
    label: '流程分类',
    prop: 'ProcessClass',
    align: 'center',
    // width: '80',
    editType: 'select',
    options: [
      { label: '', value: '' },
      { label: '任务类', value: 'T' },
      { label: '通知类', value: 'N' },
    ],
  },
  { label: '流程描述', prop: 'ProcessDefinitionDescription' },
  { label: '流程定义ID', prop: 'ProcessDefinitionId', hidden: true },
  {
    label: '管理',
    prop: 'Manage',
    width: 300,
    editType: 'custom',
    customSlot: 'action',
    actionConfig: [
      { label: '编辑草稿版', type: 'editDraft' },
      { label: '编辑最新发布版', type: 'editPublished' },
      { label: '查看全部发布版本', type: 'viewHistory' },
      { label: '更新', type: 'update' },
      { label: '复制', type: 'copy' },
    ],
  },
])
// 选中列表集合
const checkedRows = ref([])
// 选中列表集合值改变回调函数
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
// 分页大小改变回调函数
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
// 分页页码改变回调函数
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn()
}
// 列表单个cell值改变回调函数
const onCellChange = (e) => {
  apiGetModule2({ moduleEname1: e }).then((res) => {
    if (res.data.success) {
      Array.isArray(res.data.data) &&
        res.data.data.forEach((item) => {
          item.label = `【${item.moduleEname2}】${item.moduleCname2}`
          item.value = item.moduleEname2
        })

      if (Array.isArray(res.data.data)) {
        const newArray = res.data.data.map((item) => ({
          label: `【${item.moduleEname2}】${item.moduleEname2}`,
          value: item.moduleEname2,
        }))
        // 找到选定的行并更新其 moduleEname1 选项
        const selectedRow = tableRef.value.cloneTableData.find((row) => row.moduleEname1 === e)
        if (selectedRow) {
          selectedRow.moduleEname1Options = newArray
        }
      }
    }
  })
}
// 搜索查询函数
const searchFn = (type?: string, columnsVal?: any) => {
  // 页面搜索数据组装
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns
  state.query.current = pageConfig.currentPage
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  const apiUrl = proxy.$Button_api('query', route.name)
  console.log('---------api', apiUrl)
  apiRequestPost(apiUrl, state.query)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // useMessage().error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
// table保存提交
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  const apiUrl = proxy.$Button_api('save', route.name)
  console.log('api----', apiUrl)
  apiRequestPost(apiUrl, checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        tableRef.value.clearSelection()
        searchFn()
      } else {
        useMessage().error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
// 删除函数
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []

  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.formId) ids.push(item?.formId)
    })
  isTableLoading.value = true
  const apiUrl = proxy.$Button_api('delete', route.name)
  console.log('------2222', apiUrl, ids)

  apiRequestPost(apiUrl, ids)
    .then((res) => {
      isTableLoading.value = false
      searchFn()
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const handleAction = (item, rowData) => {
  // console.log('$Button_api----', proxy.$Button_api('delete'))
  // globalMethod('777')
}
const arr2 = ref([])
const getProjectname = () => {
  apiGetfrontPrjMaint().then((res) => {
    if (res.data.success) {
      Array.isArray(res.data.data) &&
        res.data.data.forEach((item) => {
          // item.label = item.moduleCname2
          item.label = `【${item.appEname}】${item.appCname}`
          item.value = item.appEname
        })

      if (Array.isArray(res.data.data)) {
        const newArray = res.data.data.map((item) => ({
          label: `【${item.appEname}】${item.appCname}`,
          value: item.appEname,
        }))
        // columns[3].editConfig.options = newArray
        // columns.editConfig.options = newArray
        // 在 DOM 更新后执行的操作
        arr2.value = newArray
      }
    }
  })
  // 如果是下拉框字段，触发接口获取选项
  //  this.fetchOptions(row旧值); // 根据旧值或上下文决定如何查询
}
const arr3 = ref([])
const getProjectname1 = () => {
  apiGetlistAllModule1().then((res) => {
    if (res.data.success) {
      Array.isArray(res.data.data) &&
        res.data.data.forEach((item) => {
          // item.label = item.moduleCname2
          item.label = item.moduleEname1
          item.value = item.moduleEname1
        })

      if (Array.isArray(res.data.data)) {
        const newArray = res.data.data.map((item) => ({
          label: item.moduleEname1,
          value: item.moduleEname1,
        }))
        // columns[3].editConfig.options = newArray
        // columns.editConfig.options = newArray
        // 在 DOM 更新后执行的操作
        arr3.value = newArray
      }
    }
  })
  // 如果是下拉框字段，触发接口获取选项
  //  this.fetchOptions(row旧值); // 根据旧值或上下文决定如何查询
}
onMounted(() => {
  getProjectname()
  getProjectname1()
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  searchFn()
})
</script>
<style lang="less" scoped>
.page-controller {
  width: 100%;
  display: flex;
  .page-form {
    flex: 1;
    margin: 0 20px;
    max-width: calc(100% - 280px);
    .page-form__query {
      width: 100%;
    }
  }
}
</style>
